<?php 
/*
 * Currently incomplete needs to extract pslip and tracking numbers
 * add tracking numbers to database
 * create pdf file and then save them while returning an array of PDF names
 * USPS PDF files partially complete, now only UPS files need to be added
 */
/**
 * @author Kartik
 * @params  shipping_label_type
 * @params int packing_slip_count
 * @params int order_id
 * @params string packing_slip_pdf_name 
 *
 */
class Packing_Model_PackingSlip{

	const INCORRECT_LABEL_TYPE = "Incorrect packing slip class selected";
	const PERMISSION_DENIED = "Permission Denied";

	/**
	 * @var Packing_Resource_[UPS/USPS/etc]
	 */
	protected $labelTypeClass;
	
	/**
	 * @var String 
	 */
	protected $labelType;
	
	/**
	 * @var String label_url
	 */
	protected $fileUrl;
	
	/**
	 * @var int
	 */
	protected $orderId;
		
	/**
	 * @var Zend_Pdf
	 */
	protected $pdfFile;
	
	/**
	 * @var array tracking_numbers
	 */
	protected $trackingArray = array();
	
//	Font Data
	/**
	 * @var Zend_Pdf_Resource_Font
	 */
	protected $_fontType = null;
	
	/**
	 * @var integer
	 */
	protected $_fontSize = 0;
	
	public function __construct($labelType){
		$this->labelType = $labelType;
		$this->labelTypeClass = "Packing_Resource_$labelType";
		$this->fileUrl = APPLICATION_PATH . "/shippinglabel/$this->labelType/";
	}
	
	public function setOrder($orderId){
		if(Doctrine_Model_Orders::userHasOrder($orderId))
			$this->orderId = $orderId;
		else 
			throw new Exception(self::PERMISSION_DENIED); 	
	}
	
	public function createPDFName($tempName) {
      return md5("$tempName");
   }
	
	public function createPdfFile(){

		if(file_exists($this->fileUrl . $this->createPdfName($this->orderId) . ".pdf")){
			return $this->createPdfName($this->orderId) . ".pdf";
			//var_dump($this->createPdfName($this->orderId) . "exists");
		}
		
		$this->PdfFile = new Zend_Pdf();
		$extractor = new Zend_Pdf_Resource_Extractor();
		
		try{
			$shipLabel = new $this->labelTypeClass('test');
			$shipLabel->setUserID();
			$shipLabel->setOrderID($this->orderId);
			
			$orderDetails = $shipLabel->getOrderDetails();
			$userDetails = $shipLabel->getCustomerDetails();
			
//			Get Weight of Order
			$shipLabel->setOrderWeight();
			$weightInPounds = $shipLabel->getWeightInPounds();
			$weightInOunces = $shipLabel->getWeightInOunces();
			
//			Calculate the maximum number of shipping labels required
			$packingSlipCounter = 1;
			$packingSlipMaxLimit = ceil($weightInPounds/30);//30 Pounds is set arbitrarily with magic number will need to be changed later
	
			do{
				$shipLabel->setRMA($packingSlipCounter);
				
				//Call USPS website and send API request.
				$shipLabel->cURLCall();
				$shipLabel->parseXML();
				//Check for errors
				if($shipLabel->checkError()){
					$error = $shipLabel->checkError();
					if(preg_match("/Address Not Found/",$error)){
						$error = "We use Post office address database to verify addresses, and they detected an error with your address. Please update and adjust your address in your user profile. After making adjustments, go back to the main window to print shipping labels. <br> <a href = '/profile.htm'> Update User Profile </a>";
					}
					echo $error;
					return;
				}
				
				//PDF image for USPS and GIF image url for UPS.... 
				$packingSlip = $shipLabel->getPackingSlip();
				
				$this->trackingArray[$packingSlipCounter] = $shipLabel->getTrackingNumber();

				//Compensating for required correction of pdflabel for USPS
				if("Packing_Resource_USPS" == $this->labelTypeClass){
					//Add PDF Stream to Page
					$packingSlip = base64_decode($packingSlip);
					$tempPdfFile = Zend_Pdf::parse($packingSlip);
					$tempPdfFile = $this->USPSLabelCorrection($tempPdfFile);
					foreach ($tempPdfFile->pages as $p) $this->PdfFile->pages[] = $extractor->clonePage($p);
					
				}elseif("Packing_Resource_UPS" == $this->labelTypeClass){
					//UPS sends a GIF Image 
					//Create temp PDF file and add image then merge with main pdf file.
					list($w_orig, $h_orig) = getimagesize($packingSlip);
					$img = imagecreatefromgif($packingSlip);
					$tci = imagecreatetruecolor($w_orig, $h_orig);
					imagecopyresampled($tci, $img, 0, 0, 0, 0, $w_orig, $h_orig, $w_orig, $h_orig);
					imagejpeg($tci, 
						$this->fileUrl . $this->createPdfName($this->orderId) 
						. "-$packingSlipCounter.jpg", 
						84);
					$image = Zend_Pdf_Image::imageWithPath(
						$this->fileUrl . $this->createPdfName($this->orderId) 
						. "-$packingSlipCounter.jpg");

					$page = $this->PdfFile->newPage(Zend_Pdf_Page::SIZE_A4);
					$pageWidth = $page->getWidth();
         			$pageHeight = $page->getHeight();
         			$imgWidth = $pageWidth;
         			$imgHeight = ($pageWidth/$w_orig)*$pageHeight;
         			// Ensures that the shipping label is in the top half;
					$page->drawImage($image, $pageWidth - $imgWidth, $pageHeight - $imgHeight, $pageWidth, $pageHeight);
					$this->PdfFile->pages[] = $page;
				}
					
				$packingSlipCounter++;
				
				/** Add tracking data to tracking database **/
				$tracking = new Doctrine_Model_Tracking();
				$tracking->orderId = $this->orderId;
				$tracking->trackId = $shipLabel->getTrackingNumber();
				$tracking->fileId = $this->createPdfName($this->orderId);
				$tracking->labelSource = $this->labelType;
				$tracking->url = $this->fileUrl;
				$tracking->save();
				var_dump($tracking);
				
			}while($packingSlipCounter <= $packingSlipMaxLimit);
			
		}catch(Exception $e){
			switch($e->getMessage()){
				case 1:
					$this->view->message = "Permission denied";
					break;
			}
		}
		
		//Save PDF File
		$this->PdfFile->save($this->fileUrl . $this->createPdfName($this->orderId) . ".pdf");
		return  $this->createPdfName($this->orderId) . ".pdf";
		//var_dump($this->createPdfName($this->orderId) . "created");
	}
	
	/**
	 * @param Zend_Pdf $pdfFile
	 * @returns Zend_Pdf $pdfFile
	 */
	public function USPSLabelCorrection(Zend_Pdf $pdfFile){

		/** 
		 * TODO add the required correction code to properly place the address elements and the postage guarantee to the pdf file
		 */
		
		return $pdfFile;
	}
}